package com.buyouchina.service.privilege.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.buyouchina.bean.privilege.Department;
import com.buyouchina.bean.privilege.User;
import com.buyouchina.service.base.DaoSupport;
import com.buyouchina.service.privilege.DepartmentService;


@Service
public class DepartmentServiceBean extends DaoSupport<Department> implements DepartmentService{

	
	
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public boolean exsit(String name) {
		long count = (Long) em.createQuery(
				"select count(o) from Department o where o.name=?1").setParameter(1, name).getSingleResult();
		return count > 0;
	}

	public boolean deleteById(Integer id) {
		Integer result = em.createQuery("delete from Department o where o.id=?1").setParameter(1, id).executeUpdate();
		return result>0;
	}


	public Department findByName(String name) {
		return (Department) em.createQuery("select o from Department o where o.name=?1")
		.setParameter(1, name).getSingleResult();
	}

	/**
	 * 查询部门（销售id 4 ,客服id 1）
	 */
	@SuppressWarnings("unchecked")
	public List<Department> getSalesDepartments() {
		return (List<Department>) em.createQuery(
		"select o from Department o where o.id in(?1,?2)")
		.setParameter(1, 1).setParameter(2, 4).getResultList();
	}

	public Department findById(Integer departmentid) {
		return (Department) em.createQuery("select o from Department o where o.id=?1")
		.setParameter(1, departmentid).getSingleResult();
	}

	public boolean deleteByDepartment(Department department) {
		try {
			for(User user : department.getUsers()){
				user.setDepartment(null);
			}
			em.remove(department);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

}
